package com.xiaoai.httpClientTestService.httpclient.javaf;

import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.BasicNameValuePair;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class HttpclientPostParamForm {

    public static void main(String[] args) throws Exception {
        // 创建httpget对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建请求对象 设置url
        HttpPost httpPost = new HttpPost("http://localhost:8080/test/getpPostParam");

        // ---list集合，封装表单中参数
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("name","xiaoai"));
        params.add(new BasicNameValuePair("sex","nan"));
        // ---创建表单Entity对象
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, Charset.defaultCharset());
        // ---设置表单的Entity对象到post请求
        httpPost.setEntity(formEntity);

        CloseableHttpResponse response = null;
        // 发起请求，获取response
        response = httpClient.execute(httpPost);
        // 解析
        System.out.println(response.getCode()+"=========");
        if (response.getCode() == 200){
            String content  = EntityUtils.toString(response.getEntity(),"utf8");
            System.out.println(content);
        }
        response.close();
        httpClient.close();
    }
}
